package com.Nahida.NaHome.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.utils.widget.ImageFilterView;
import androidx.recyclerview.widget.RecyclerView;

import com.Nahida.NaHome.R;
import com.Nahida.NaHome.util.MsgUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.List;

public class RealAppsAdapter extends RecyclerView.Adapter<RealAppsAdapter.AppListHolder> {

    Context context;
    List<ResolveInfo> appInfo;

    public RealAppsAdapter(Context context, List<ResolveInfo> appInfo) {
        this.context = context;
        this.appInfo = appInfo;
    }

    @NonNull
    @Override
    public AppListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.context).inflate(R.layout.cell_app_list,parent,false);
        return new AppListHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AppListHolder holder, int position) {
        ActivityInfo activityInfo = appInfo.get(position).activityInfo;

        Glide.with(context).load(activityInfo.loadIcon(context.getPackageManager()))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(holder.appIcon);
        holder.appName.setText(activityInfo.loadLabel(context.getPackageManager()));

        holder.appCard.setOnClickListener(view -> {
            Intent intent = new Intent();
            Log.e("debug",activityInfo.packageName + " | " +activityInfo.name);
            intent.setClassName(activityInfo.packageName,activityInfo.name);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                context.startActivity(intent);
            } catch (Exception e){
                MsgUtil.err(e,context);
            }
        });
    }

    @Override
    public int getItemCount() {
        return appInfo.size();
    }

    public static class AppListHolder extends RecyclerView.ViewHolder{
        ImageFilterView appIcon;
        TextView appName;
        View appCard;

        public AppListHolder(@NonNull View itemView) {
            super(itemView);
            appName = itemView.findViewById(R.id.appName);
            appIcon = itemView.findViewById(R.id.appIcon);
            appCard = itemView.findViewById(R.id.appCard);
        }
    }
}
